/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} start
 * @return {number}
 */
var amountOfTime = function (root, start) {
	const graph = new Map()
	const dfs = (node) => {
		;[node.left, node.right].forEach((child) => {
			if (child !== null) {
				graph.has(node.val)
					? graph.get(node.val).push(child.val)
					: graph.set(node.val, [child.val])
				graph.has(child.val)
					? graph.get(child.val).push(node.val)
					: graph.set(child.val, [node.val])

				dfs(child)
			}
		})
	}
	dfs(root)
	const q = [[start, 0]]
	const visited = new Set([start])
	let time = 0
	while (q.length) {
		const [nodeVal, currTime] = q.shift()
		time = currTime
		if (graph.has(nodeVal)) {
			graph.get(nodeVal).forEach((childValue) => {
				if (!visited.has(childValue)) {
					q.push(childValue, currTime + 1)
					visited.add(childValue)
				}
			})
		}
	}
	return time
}
